<template>
 <el-form :inline="true" :model="page" class="demo-form-inline">
    <el-form-item label="商品名称">
      <el-input v-model="page.ShopName" placeholder="请输入商品名称" clearable style="width: 150px;"/>
    </el-form-item>

    <el-form-item label="生产批次">
      <el-input v-model="page.Batch" placeholder="请输入生产批次" clearable style="width: 150px;"/>
    </el-form-item>

    <el-form-item label="保质期(天)">
      <el-input v-model="page.PeriodTime" placeholder="请输入保质期" clearable style="width: 150px;"/>
    </el-form-item>

    <el-form-item label="生产许可证号">
      <el-input v-model="page.License" placeholder="请输入生产许可证号" clearable style="width: 160px;"/>
    </el-form-item>

    <el-form-item label="生产企业">
      <el-input v-model="page.ManuName" placeholder="请输入生产企业" clearable style="width: 150px;"/>
    </el-form-item>
    
      
    <el-form-item>
      <el-button type="primary" @click="getpeoductlist()">查询</el-button>
    </el-form-item>
  </el-form>

    <el-button type="primary"  @click="handleDeleteSelected">
      删除
    </el-button>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="date" type="index" label="序号" width="80" />
      <el-table-column prop="shopName" label="商品名称" width="180" />
      <el-table-column prop="batch" label="生产批次" width="180" />
      <el-table-column prop="periodTime" label="保质期(天)" width="180" />
      <el-table-column prop="license" label="生产许可证号" width="180" />
      <el-table-column prop="manuName" label="生产企业" width="220" />
      <el-table-column prop="improve" label="信息完善度" width="110">
        <template v-slot="scope">
            <p v-if="scope.row.improve==100" style="color:green;">{{scope.row.improve}}%</p>
            <p v-else style="color:red;">{{scope.row.improve}}%</p>
        </template>
      </el-table-column>
      <el-table-column prop="createPeople" label="创建人" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template v-slot="scope">
          {{ scope.row.createTime.substring(0, 10) + ' ' + scope.row.createTime.substring(11, 19) }}
        </template>
      </el-table-column>
      <el-table-column prop="updatePeople" label="修改人" width="180" />
      <el-table-column prop="updateTime" label="修改时间" width="180">
        <template v-slot="scope">
          <p v-if="scope.row.updateTime != null">
            {{ scope.row.updateTime.substring(0, 10) + ' ' + scope.row.updateTime.substring(11, 19) }}
          </p>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="180">
        <template v-slot="scope">
          <el-button link type="primary" size="small" @click="deletepro(scope.row.proId)">删除</el-button>
          <el-button link type="primary" size="small" @click="updatepro(scope.row)">修改</el-button>
          <el-button link type="primary" size="small" @click="getxiangqing(scope.row.batch,scope.row.proId)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
<!-- 分页 -->
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page.Pageindex"
      v-model:page-size="page.Pagesize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
  </div>
<!-- 修改弹窗 -->

<el-dialog v-model="dialogFormVisible" title="修改商品" width="700" center>
    <el-form :model="ruleForm">       
        <el-form-item label="商品名称" prop="shopId">
        <el-select v-model="ruleForm.shopId"  placeholder="请选择商品名称">
          <el-option v-for="item in Stposc" :label="item.shopName" :value="item.shopId" />
        </el-select>
    </el-form-item>

    <el-form-item label="生产批次">
      <el-input v-model="ruleForm.batch" />
    </el-form-item>

    <el-form-item label="保质期(天)">
      <el-input v-model="ruleForm.periodTime" />
    </el-form-item>

    <el-form-item label="生产许可证书">
      <el-input v-model="ruleForm.license" />
    </el-form-item>

    <el-form-item label="生产企业">
      <el-input v-model="ruleForm.manuName" />
    </el-form-item>
    <el-form-item label="封面页">
    <el-upload
    class="avatar-uploader"
    action="http://localhost:5013/api/Pic/UploadImage/upload"
    :data="{ picType: 101, batch: '20170419' }"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="picra.picaddr" :src="picra.picaddr" class="avatar" />
    
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</el-form-item>
</el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click=" getupdatepro()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>


  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import axios from 'axios';
import { ElMessage ,ElMessageBox} from 'element-plus';
import {useCounterStore} from '@/stores/counter'
import type { UploadProps } from 'element-plus'
import { useRouter } from 'vue-router';
import { te } from 'element-plus/es/locales.mjs';


let Stroe=useCounterStore();
let router=useRouter();

//分页监听事件
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}


  // 表格数据
  const tableData = ref([]);
  
  // 选中的行数据
  const selectedRows = ref([]);
  
  // 监听多选事件
  const handleSelectionChange = (selection:any) => {
    selectedRows.value = selection;
    console.log('选中的行数据:', selectedRows.value); // 打印选中的数据，检查字段名称
    const selectedIds = selection.map((row:any) => row.proId || row.proId); // 使用 id 或 productId
    console.log('选中的行 id:', selectedIds);
  };
  
  // 删除选中的行(批量删除)
  const handleDeleteSelected = () => {
    if (selectedRows.value.length == 0) {
      ElMessage.error('请先选择要删除的行');
      return;
    }
    const selectedIds = selectedRows.value.map((row:any) => row.proId || row.proId); // 使用 id 或 productId
    console.log('选中的行 id:', selectedIds);
    ElMessageBox.confirm(
    '您确定要操作吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios({
        url:'http://localhost:5013/api/Shop/DeleteProduct',
        method:'put',
        data:{
            proIds:selectedIds
        }
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage({
        type: 'success',
        message: '操作成功',
      })
      getpeoductlist();
        }
    })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
  };
//删除单条数据
const deletepro=(proId:any)=>{
    const selectedIds = [proId];
    ElMessageBox.confirm(
    '您确定要操作吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios({
        url:'http://localhost:5013/api/Shop/DeleteProduct',
        method:'put',
        data:{
            proIds:selectedIds
        }
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage({
        type: 'success',
        message: '操作成功',
      })
      getpeoductlist();
        }
    })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

  // 获取表格数据
  const getpeoductlist = () => {
    axios({
      url: 'http://localhost:5011/api/Product/QueryProduct',
      method: 'get',
      params: {
        ShopName: page.ShopName,
        Batch: page.Batch,
        PeriodTime: page.PeriodTime,
        ManuName: page.ManuName,
        Pageindex: page.Pageindex,
        Pagesize: page.Pagesize,
      },
    }).then((res) => {
      if (res.data.code === 101) {
        console.log('接口返回的数据:', res.data.list); // 打印数据，检查是否有 id
        tableData.value = res.data.list;
        page.totalcount = res.data.totalCount;
        page.totalpage = res.data.totalPage;
      }
    });
  };
  
  // 分页数据
  const page = reactive({
    ShopName: '',
    Batch: '',
    PeriodTime: '',
    ManuName: '',
    License: '',
    Pageindex: 1,
    Pagesize: 15,
    totalcount: 0,
    totalpage: 0,
  });
  
  // 初始化加载数据
  onMounted(() => {
    getpeoductlist();
    getshoplist();
    selePic();
  });

  //弹框数据
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'  
const ruleForm = reactive({
    proId:'',
    shopId: '',
    batch: '',
    periodTime: '',
    manuName: '',
    improve: 0,
    license:'',
    updatePeoplePeople:Stroe.CurrLoginUser.UserName,
    isDelete: 0,
   
  })
  //修改
  const updatepro=(row:any)=>{
    ruleForm.proId=row.proId,
    ruleForm.shopId=row.shopId;
    ruleForm.batch=row.batch;
    ruleForm.periodTime=row.periodTime;
    ruleForm.manuName=row.manuName;
    ruleForm.improve=row.improve;
    ruleForm.license=row.license;
    //imageUrl.value=picra.picaddr,
    dialogFormVisible.value=true;
   
  }
//修改方法
const getupdatepro=()=>{
    axios({
        url:'http://localhost:5013/api/Shop/UpdateProduct',
        method:'put',
        data:ruleForm
    })
    .then(res=>{
        if(res.data.code==101){
            console.log('修改数据',res)
            ElMessage.success('修改成功');
            dialogFormVisible.value=false;
            getpeoductlist();
        }
        else{
            ElMessage.error("失败")
        }
    })
    .catch(error=>{
        console.log(error)
    })
}

const getxiangqing=(batch:any,proId:any)=>{
  console.log('生产批次',batch)
    router.push({
     
    name:'xiangqing',
    query:{
      batch:batch,
      proId:proId
    }
    })
}






  const imageUrl = ref('')
  //图片
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('仅支持 JPG/PNG 格式');
    return false;
  }else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  console.log(rawFile)
  return true
}

//商品名称
const Stposc=ref<any>([]);
const getshoplist=()=>{
    axios({
    url:'http://localhost:5011/api/Product/QueryShop',
    method:'get',
    })
    .then(res=>{
        if(res.data.code==101){
            Stposc.value=res.data.list;
        }
    })
}



const syoo=reactive({
    PicType:101,
    Batch:'20170419'
})
const picra=reactive({
    picaddr:''
});
//查询图片
const selePic=()=>{
    axios({
        url:'http://localhost:5013/api/Pic/QueryPic',
        method:'get',
        params:{
            PicType:syoo.PicType,
            Batch:syoo.Batch
        }
    })
    .then(res=>{
        console.log(syoo.PicType)
        console.log(syoo.Batch)
        if(res.data.code==101){
            console.log(res);
            picra.picaddr=res.data.list[0].pictureAddr
            console.log(picra.picaddr)
        }
    })
}

  </script>
  <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>